package com.example.project7;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.project7.utils.SharedPreferencesUtil;
import com.example.project7.viewmodel.AutoLoginState;
import com.example.project7.viewmodel.LoginState;
import com.example.project7.viewmodel.LoginViewModel;
import com.example.project7.viewmodel.RegisterState;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private EditText etUsername;
    private EditText etPassword;
    private CheckBox cbAgreeTerms;
    private CheckBox cbAutoLogin;
    private Button btnLogin;
    private TextView tvRegisterHint;
    private ImageView ivPasswordToggle;
    private ProgressBar pbLoading;
    private TextView tvLoadingText;
    private boolean isPasswordVisible = false;
    private Handler handler = new Handler(Looper.getMainLooper());
    private LoginViewModel loginViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        setContentView(R.layout.activity_login);

        // 初始化ViewModel
        loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);

        // 初始化控件
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        cbAgreeTerms = findViewById(R.id.cb_agree_terms);
        cbAutoLogin = findViewById(R.id.cb_auto_login);
        btnLogin = findViewById(R.id.btn_login);
        tvRegisterHint = findViewById(R.id.tv_register_hint);
        ivPasswordToggle = findViewById(R.id.iv_password_toggle);
        pbLoading = findViewById(R.id.pb_loading);
        tvLoadingText = findViewById(R.id.tv_loading_text);

        // 检查自动登录
        checkAutoLogin();

        // 设置输入框的TextWatcher，实现自动去除空格和状态检查
        setupTextWatchers();

        // 设置协议勾选框的监听
        setupCheckboxListener();

        // 设置密码显示/隐藏切换
        setupPasswordToggle();

        // 登录按钮点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleLogin();
            }
        });

        // 注册提示点击事件
        tvRegisterHint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleRegister();
            }
        });

        // 观察登录状态
        observeLoginState();

        // 观察注册状态
        observeRegisterState();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        // 清理Handler回调，防止内存泄漏
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    /**
     * 检查自动登录
     */
    private void checkAutoLogin() {
        // 观察自动登录状态
        loginViewModel.getAutoLoginState().observe(this, autoLoginState -> {
            if (autoLoginState instanceof AutoLoginState.Loading) {
                // 自动登录检查中
                showLoadingState(true, getString(R.string.logging_in));
            } else if (autoLoginState instanceof AutoLoginState.Success) {
                // 自动登录成功，跳转到主页面
                showLoadingState(false, null);
                navigateToMain();
            } else if (autoLoginState instanceof AutoLoginState.Error) {
                // 自动登录失败，显示登录页面
                showLoadingState(false, null);
                AutoLoginState.Error errorState = (AutoLoginState.Error) autoLoginState;
                Log.d(TAG, "自动登录失败: " + errorState.getErrorMessage());
            } else if (autoLoginState instanceof AutoLoginState.NotEnabled) {
                // 自动登录未启用
                showLoadingState(false, null);
                Log.d(TAG, "自动登录未启用");
            }
        });

        // 执行自动登录检查
        loginViewModel.autoLogin();
    }

    /**
     * 设置输入框的TextWatcher
     */
    private void setupTextWatchers() {
        // 用户名输入框TextWatcher
        etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                // 自动去除前后空格
                String text = s.toString();
                String trimmed = text.trim();
                if (!text.equals(trimmed)) {
                    etUsername.setText(trimmed);
                    etUsername.setSelection(trimmed.length());
                }
                updateLoginButtonState();
            }
        });

        // 密码输入框TextWatcher
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                updateLoginButtonState();
            }
        });
    }

    /**
     * 设置协议勾选框监听
     */
    private void setupCheckboxListener() {
        cbAgreeTerms.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                updateLoginButtonState();
            }
        });
    }

    /**
     * 设置密码显示/隐藏切换
     */
    private void setupPasswordToggle() {
        ivPasswordToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPasswordVisible) {
                    // 隐藏密码
                    etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    ivPasswordToggle.setImageResource(R.drawable.ic_visibility_off);
                    isPasswordVisible = false;
                } else {
                    // 显示密码
                    etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    ivPasswordToggle.setImageResource(R.drawable.ic_visibility);
                    isPasswordVisible = true;
                }
                // 移动光标到末尾
                etPassword.setSelection(etPassword.getText().length());
            }
        });
    }

    /**
     * 更新登录按钮状态
     */
    private void updateLoginButtonState() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        boolean isAgreeTerms = cbAgreeTerms.isChecked();

        // 只有当用户名、密码都不为空且勾选了协议时，登录按钮才可用
        boolean shouldEnable = !username.isEmpty() && !password.isEmpty() && isAgreeTerms;
        btnLogin.setEnabled(shouldEnable);
    }

    /**
     * 处理登录逻辑
     */
    private void handleLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        boolean isAgreeTerms = cbAgreeTerms.isChecked();
        boolean isAutoLogin = cbAutoLogin.isChecked();

        // 输入验证
        if (username.isEmpty()) {
            Toast.makeText(this, R.string.please_enter_username, Toast.LENGTH_SHORT).show();
            return;
        }

        if (password.isEmpty()) {
            Toast.makeText(this, R.string.please_enter_password, Toast.LENGTH_SHORT).show();
            return;
        }

        if (!isAgreeTerms) {
            Toast.makeText(this, R.string.please_agree_terms, Toast.LENGTH_SHORT).show();
            return;
        }

        // 保存自动登录状态
        loginViewModel.saveAutoLoginState(isAutoLogin);

        // 显示加载状态
        showLoadingState(true, getString(R.string.logging_in));

        // 执行登录
        loginViewModel.login(username, password);
    }

    /**
     * 处理注册逻辑
     */
    private void handleRegister() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 输入验证
        if (username.isEmpty()) {
            Toast.makeText(this, R.string.please_enter_username, Toast.LENGTH_SHORT).show();
            return;
        }

        if (password.isEmpty()) {
            Toast.makeText(this, R.string.please_enter_password, Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示加载状态
        showLoadingState(true, getString(R.string.registering));

        // 执行注册
        loginViewModel.register(username, password);
    }

    /**
     * 观察登录状态
     */
    private void observeLoginState() {
        loginViewModel.getLoginState().observe(this, loginState -> {
            if (loginState instanceof LoginState.Loading) {
                // 登录中
                showLoadingState(true, getString(R.string.logging_in));
            } else if (loginState instanceof LoginState.Success) {
                // 登录成功
                showLoadingState(false, null);
                Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
                navigateToMain();
            } else if (loginState instanceof LoginState.Error) {
                // 登录失败
                showLoadingState(false, null);
                LoginState.Error errorState = (LoginState.Error) loginState;
                String errorMessage = getString(R.string.login_failed, errorState.getErrorMessage());
                Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 观察注册状态
     */
    private void observeRegisterState() {
        loginViewModel.getRegisterState().observe(this, registerState -> {
            if (registerState instanceof RegisterState.Loading) {
                // 注册中
                showLoadingState(true, getString(R.string.registering));
            } else if (registerState instanceof RegisterState.Success) {
                // 注册成功
                showLoadingState(false, null);
                Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
                navigateToMain();
            } else if (registerState instanceof RegisterState.Error) {
                // 注册失败
                showLoadingState(false, null);
                RegisterState.Error errorState = (RegisterState.Error) registerState;
                String errorMessage = getString(R.string.register_failed, errorState.getErrorMessage());
                Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 显示/隐藏加载状态
     * @param show 是否显示加载状态
     * @param loadingText 加载提示文本
     */
    private void showLoadingState(boolean show, String loadingText) {
        if (show) {
            // 显示加载状态
            pbLoading.setVisibility(View.VISIBLE);
            tvLoadingText.setText(loadingText);
            tvLoadingText.setVisibility(View.VISIBLE);
            btnLogin.setText(""); // 清空按钮文本
            
            // 禁用按钮和输入框，防止重复点击
            btnLogin.setEnabled(false);
            etUsername.setEnabled(false);
            etPassword.setEnabled(false);
            cbAgreeTerms.setEnabled(false);
            cbAutoLogin.setEnabled(false);
            tvRegisterHint.setEnabled(false);
        } else {
            // 隐藏加载状态
            pbLoading.setVisibility(View.GONE);
            tvLoadingText.setVisibility(View.GONE);
            btnLogin.setText(R.string.login); // 恢复按钮文本
            
            // 恢复控件状态
            etUsername.setEnabled(true);
            etPassword.setEnabled(true);
            cbAgreeTerms.setEnabled(true);
            cbAutoLogin.setEnabled(true);
            tvRegisterHint.setEnabled(true);
            
            // 更新登录按钮状态
            updateLoginButtonState();
        }
    }

    /**
     * 跳转到主页面
     */
    private void navigateToMain() {
        String username = etUsername.getText().toString().trim();
        if (username.isEmpty()) {
            username = SharedPreferencesUtil.getUsername(this);
        }
        
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra("username", username);
        startActivity(intent);
        finish(); // 关闭登录页面，防止返回键回到登录页
    }
}